import time

import pydantic
from sqlalchemy import select, update

from forward.api.admin.schemas.decorate import (
    DecoratePageSaveInSchema,
    DecoratePageDetailOutSchema,
)
from forward.dependencies.database import db
from forward.model.tables.decorate import DecoratePageModel


class DecoratePageService:

    async def detail(self, _id: int) -> DecoratePageDetailOutSchema:
        page_detail = await db.fetch_one(
            select(DecoratePageModel)
            .select_from(DecoratePageModel)
            .where(DecoratePageModel.id == _id)
        )
        assert page_detail, "数据不存在！"
        return DecoratePageDetailOutSchema.model_validate(
            page_detail, from_attributes=True
        )

    async def save(self, save_in: DecoratePageSaveInSchema):
        page_detail = await db.fetch_one(
            select(DecoratePageModel)
            .select_from(DecoratePageModel)
            .where(DecoratePageModel.id == save_in.id)
        )
        assert page_detail, "数据不存在！"
        page_edit = save_in.model_dump()
        return await db.execute(
            update(DecoratePageModel)
            .where(DecoratePageModel.id == save_in.id)
            .values(**page_edit)
        )

    @classmethod
    async def instance(cls):
        """实例化"""
        return cls()
